﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.LIB;

using Teigha.Core;
using Teigha.TD;

namespace YJKPretreatmentModeling.Cmd
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	internal class CmdSplitCADBlockFrameImp2RevitView : IExternalCommand
	{
		[DllImport("user32.dll", EntryPoint = "SendMessageA")]
		public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
            OdDbObjectId idEnt = OdDbObjectId.kNull;


			OpenFileDialog openFileDialog = new OpenFileDialog();
			openFileDialog.Filter = "DWG Files (*.dwg)|*.dwg";
			DWG2RevitLevelConfigForm dwg2RevitLevelConfigForm = null;
			if (openFileDialog.ShowDialog() == DialogResult.OK)
			{
				try
				{
					string fileName = openFileDialog.FileName;
					DWG2RevitLevelConfigForm.b = false;
					dwg2RevitLevelConfigForm = new DWG2RevitLevelConfigForm(commandData, fileName);
					if (!DWG2RevitLevelConfigForm.bOK)
					{
						return Autodesk.Revit.UI.Result.Failed;
					}
					if (CmdSplitCADBlockFrameImp2RevitView.m_hWndRevit == null)
					{
						CmdSplitCADBlockFrameImp2RevitView.m_hWndRevit = new YJKWindowHandle(Process.GetCurrentProcess().MainWindowHandle);
					}
					dwg2RevitLevelConfigForm.ShowDialog(CmdSplitCADBlockFrameImp2RevitView.m_hWndRevit);
					int wMsg = 7;
					CmdSplitCADBlockFrameImp2RevitView.SendMessage(CmdSplitCADBlockFrameImp2RevitView.m_hWndRevit.Handle, wMsg, IntPtr.Zero, IntPtr.Zero);
					return Autodesk.Revit.UI.Result.Succeeded;
				}
				catch (Exception ex)
				{
                    string sss = ex.Message;
					YJKMessageBox.Warning("由于DWG图纸存在问题，导致失败！请使用CAD‘核查’、‘修复’命令对DWG图纸进行处理。");
					return Autodesk.Revit.UI.Result.Failed;
				}
				finally
				{
					if (dwg2RevitLevelConfigForm != null && !dwg2RevitLevelConfigForm.IsDisposed)
					{
						dwg2RevitLevelConfigForm.DisposeMember();
						dwg2RevitLevelConfigForm.Dispose();
					}
				}
				return Autodesk.Revit.UI.Result.Failed;
			}
			return Autodesk.Revit.UI.Result.Failed;
		}

		private static YJKWindowHandle m_hWndRevit;
	}
}
